<!-- 推广佣金管理 -->
<template>
    <div >
        <a-card :bordered="false" title="数据汇总">
            <a-row>
                <a-col :sm="8" :xs="24">
                    <Info title="总笔数（笔）" :value="totalCount"/>
                </a-col>
                <a-col :sm="8" :xs="24">
                    <Info title="待发放笔数（笔）" :value="waitIssuedCount"/>
                </a-col>
                <a-col :sm="8" :xs="24">
                    <Info title="成功发放笔数（笔）" :value="successIssuedCount" :rightBordered="false" />
                </a-col>
            </a-row>
            <a-row>
                <a-col :sm="8" :xs="24">
                    <Info title="实发总金额（￥）" :value="totalActualAmount" :desc="'（佣金总金额：' + totalAwardAmount + '）'" :btmBordered="false"/>
                </a-col>
                <a-col :sm="8" :xs="24">
                    <Info title="待发放金额（￥）" :value="waitIssuedActualAmount" :desc="'（待发佣金：' + waitIssuedAwardAmount + '）'" :btmBordered="false"/>
                </a-col>
                <a-col :sm="8" :xs="24">
                    <Info title="发放成功金额（￥）" :value="successIssuedActualAmount" :desc="'（发放成功佣金：' + successIssuedAwardAmount + '）'" :rightBordered="false" :btmBordered="false"/>
                </a-col>
            </a-row>
        </a-card>
        <a-card :bordered="false" title="数据列表">
            <div class='table-page-search-wrapper'>
                <a-form layout='inline'>
                <a-row :gutter='48'>
                        <a-col :md='8' :sm='24'>
                            <a-form-item label="">
                                <a-input-search v-model="userInfoQry" placeholder="姓名/身份证/手机号" allow-clear @search="getData"></a-input-search>
                            </a-form-item>
                        </a-col>
                        <a-col :md='8' :sm='24'>
                            <a-form-item label="所属客户">
                                <a-input v-model="customerName" placeholder="请输入所属客户" allow-clear></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :md='8' :sm='24'>
                            <a-form-item label="项目名称">
                                <a-input v-model="projectName" placeholder="请输入项目名称" allow-clear></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :md='8' :sm='24'>
                            <a-form-item label="结算单名称">
                                <a-input v-model="settlementName" placeholder="请输入结算单名称" allow-clear></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :md='8' :sm='24'>
                            <a-form-item label="结算时间">
                                <a-range-picker @change="onSettlementDateChange" allow-clear/>
                            </a-form-item>
                        </a-col>
                        <a-col :md='8' :sm='24'>
                            <a-form-item label="发放时间">
                                <a-range-picker @change="onDateChange" allow-clear/>
                            </a-form-item>
                        </a-col>
                        <a-col :md='16' :sm='24'>
                        </a-col>
                        <a-col :md='8' :sm='24'>
                            <a-form-item >
                                <a-button type='primary' @click="getData">查询</a-button>
                                <!-- <a-button style="margin-left: 20px" type='' @click="download">导出</a-button> -->
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
            <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small" :scroll="{ x: 1500, }">
                <div slot="platformRate" slot-scope="platformRate">
                    <div>{{platformRate}}%</div>
                </div>
                <div slot="awardRate" slot-scope="awardRate">
                    <div>{{awardRate}}%</div>
                </div>
                <div slot="serviceRate" slot-scope="serviceRate">
                    <div>{{serviceRate}}%</div>
                </div>
                <div slot="awardType" slot-scope="awardType">
                    <div v-for="(item,i) in awardTypeList" :key="item.id">
                        <a-tag v-if="item.id == awardType" :color="colors[i%13]">{{item.name}}</a-tag>
                    </div>
                </div>
                <div slot="state" slot-scope="state">
                    <div v-for="(item,i) in stateList" :key="item.id">
                        <a-tag v-if="item.id == state" :color="colors[i%13]">{{item.name}}</a-tag>
                    </div>
                </div>
                <div slot="operation" slot-scope="text,record">
                    <div class="editable-row-operations">
                        <a-button v-if="record.state == 1" type="link" @click="pay(record)">发放</a-button>
                        <a-button v-if="record.state == 1" @click="refuseE(record)" type="link">驳回</a-button>
                    </div>
                </div>
            </a-table>
        </a-card>

        <!-- 拒绝原因 -->
        <a-modal 
            v-model="visible" 
            title="拒绝原因"
            @ok="handleOk" 
            @cancel="visible = false">
            <div>
                <a-form-model :model="refuse" ref="ruleForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
                    <a-form-model-item label="拒绝原因" prop="refuseReason">
                        <a-textarea v-model="refuse.refuseReason" placeholder="请输入拒绝原因" :auto-size="{ minRows: 4, maxRows: 6 }" allow-clear/>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>

        <!-- 去支付 -->
        <a-modal 
            v-model="payVisible" 
            title="确认支付"
            @ok="payHandleOk" 
            width="75%"
            @cancel="payVisible = false">
            <div>
                <a-descriptions :title="`结算金额${paySettlement.settlementAmount}`">
                    <a-descriptions-item label="奖励金额">{{paySettlement.awardAmount}}</a-descriptions-item>
                    <a-descriptions-item label="奖励比例">{{paySettlement.awardRate}}%</a-descriptions-item>
                    <a-descriptions-item label="实发金额">{{paySettlement.amount}}</a-descriptions-item>
                    <a-descriptions-item label="结算单名称">{{paySettlement.settlementName}}</a-descriptions-item>
                    <a-descriptions-item label="姓名">{{paySettlement.realName}}</a-descriptions-item>
                    <a-descriptions-item label="身份证号">{{paySettlement.idCard}}</a-descriptions-item>
                    <a-descriptions-item label="奖励类型">{{paySettlement.awardType == '1' ? '直推' : '间推'}}</a-descriptions-item>
                    <a-descriptions-item label="是否首次结算">{{paySettlement.firstGrant == '1' ? '是' : '否'}}</a-descriptions-item>
                </a-descriptions>
                <a-form-model :label-col="{ span:3 }" :wrapper-col="{ span: 15 }" v-if="hasPayPassword && needPayPassword">
                    <a-form-model-item label="支付密码" labelAlign="left">
                        <a-input v-model="payPassword" placeholder="请输入支付密码" allow-clear/>
                    </a-form-model-item>
                </a-form-model>
                <a-divider/>
                <div>可用支付账户</div>
                <a-radio-group v-model="accountId" @change="selAccount">
                    <a-radio :style="radioStyle" v-for="account in accountList" :key="account.id" :value="account.id">账户名称{{account.accountName}}({{account.bankAccount}})，联动设置：{{account.linkageType |linkageTypeFilter}}</a-radio>
                </a-radio-group>
            </div>
        </a-modal>
    </div>
</template>

<script>
import Info from '../../Statistics/components/Info';
import { columns } from './table';
import { queryAwardRecordGather , refuseReceiveAward , queryAccountListByAwardAlive , payAwardOrder } from '@/api/services/statistics';
import { getHasPayPassword } from '@/api/services/account';
export default {
    components: {
        Info,
    },
    data () {
        return {
            dataList: [],
            page: 1,
            size: 10,
            total: 0,
            isload: false,
            columns,
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            issuedStartTime: '', // 发放开始时间
            issuedEndTime: '', // 发放结束时间
            settlementStartTime: '', // 结算开始时间
            settlementEndTime: '', // 结算结束时间
            userInfoQry: '', // 用户信息，姓名，身份证号，手机号
            customerName: '', // 客户名称
            settlementName: '', // 结算单名称
            projectName: '', // 项目名称
            stateList: [
                { id: 0, name: '待提交'},
                { id: 1, name: '待发放'},
                { id: 2, name: '发放中'},
                { id: 3, name: '发放失败'},
                { id: 4, name: '发放成功'},
            ],
            awardTypeList: [
                { id: 1, name: '直推'},
                { id: 2, name: '间推'},
            ],
            totalCount: 0, // 总笔数
            waitIssuedCount: 0, // 待发放笔数
            successIssuedCount: 0, // 发放成功笔数
            totalActualAmount: 0, // 总实发金额
            waitIssuedActualAmount: 0, // 待发放金额
            successIssuedActualAmount: 0, // 成功发放金额
            totalAwardAmount: 0, // 总佣金金额
            waitIssuedAwardAmount: 0, // 代发佣金金额
            successIssuedAwardAmount: 0, // 发放成功佣金金额
            awardId: '', // 推广佣金结算单ID
            visible: false,
            rules: {
                refuseReason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]
            },
            refuse: {
                refuseReason: '',
            },
            payVisible: false,
            accountList: [],
            paySettlement: {
                id: '',
                settlementAmount: '',
                awardAmount: '',
                awardRate: '',
                amount: '', 
                settlementName: '',
                realName: '',
                idCard: '',
                awardType: '1',
                firstGrant: '0',
            },
            accountId: undefined,
            radioStyle: {
                display: 'block',
                height: '30px',
                lineHeight: '30px',
            },
            payPassword: '',
            hasPayPassword: false,
            needPayPassword: false,
        };
    },
    created(){
        this.getData();
    },
    methods: {
        // 结算日期筛选
        onSettlementDateChange(date,dateStr){
            if(date.length > 0){
                this.settlementStartTime = `${dateStr[0]}`
                this.settlementEndTime = `${dateStr[1]}`
            }else{
                this.settlementStartTime = ''
                this.settlementEndTime = ''
            }
            this.getData()
        },
        // 发放日期筛选
        onDateChange(date,dateStr){
            console.log(date,dateStr)
            if(date.length > 0){
                this.issuedStartTime = `${dateStr[0]}`
                this.issuedEndTime = `${dateStr[1]}`
            }else{
                this.issuedStartTime = ''
                this.issuedEndTime = ''
            }
            this.getData()
        },
        // 获取账户列表数据
        getData(){
            let _this = this;
            _this.isload = true;
            const params = {
                'pageIndex': _this.page,
                'pageSize': _this.size,
                'issuedStartTime': _this.issuedStartTime,
                'issuedEndTime': _this.issuedEndTime,
                'settlementStartTime': _this.settlementStartTime,
                'settlementEndTime': _this.settlementEndTime,
                'userInfoQry': _this.userInfoQry,
                'customerName': _this.customerName,
                'settlementName': _this.settlementName,
                'projectName': _this.projectName,
            }
            queryAwardRecordGather(params)
            .then(res => {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data.records
                    _this.total = res.data.totalCount
                    // 数据统计
                    _this.waitIssuedCount = res.data.awardRecordStats.waitIssuedCount
                    _this.successIssuedCount = res.data.awardRecordStats.successIssuedCount
                    _this.totalActualAmount = res.data.awardRecordStats.totalActualAmount
                    _this.waitIssuedActualAmount = res.data.awardRecordStats.waitIssuedActualAmount
                    _this.successIssuedActualAmount = res.data.awardRecordStats.successIssuedActualAmount
                    _this.totalCount = res.data.awardRecordStats.totalCount
                    _this.totalAwardAmount = res.data.awardRecordStats.totalAwardAmount
                    _this.waitIssuedAwardAmount = res.data.awardRecordStats.waitIssuedAwardAmount
                    _this.successIssuedAwardAmount = res.data.awardRecordStats.successIssuedAwardAmount
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 驳回
        refuseE(item){
            this.awardId = item.id;
            this.visible = true;
        },
        handleOk(){
            let _this = this
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    const params = {
                        'awardId': _this.awardId,
                        'refuseReason': _this.refuse.refuseReason
                    }
                    refuseReceiveAward(params)
                    .then(res=>{
                        if(res.success){
                            _this.visible = false;
                            _this.getData();
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '操作成功',
                                duration: 8
                            })
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },// 去支付
        pay(item){
            let _this = this;
            _this.paySettlement = JSON.parse(JSON.stringify(item));
            _this.accountId = undefined;
            _this.accountList = [];
            queryAccountListByAwardAlive(item.id)
            .then(res => {
                if(res.success){
                    _this.accountList = res.data
                    _this.payVisible = true;
                    if(res.data.length > 0){
                        _this.accountId = res.data[0].id
                        _this.getHasPaypassword(_this.accountId)
                        if(res.data[0].needDealPassword == '1'){
                            _this.needPayPassword = true;
                        }else{
                            _this.needPayPassword = false;
                        }
                    }
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 确认支付
        payHandleOk(){
            let _this = this;
            if(_this.accountId == undefined){
                _this.$message.warning('请先选择支付账户！');
                return;
            }
            if(_this.hasPayPassword && _this.needPayPassword){
                if(_this.payPassword == ''){
                    _this.$message.warning('请输入交易密码！');
                    return;
                }
            }
            const params = {
                'awardId': _this.paySettlement.id,
                'accountId': _this.accountId,
                'payPassword': _this.payPassword,
            }
            payAwardOrder(params)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '已提交支付',
                        duration: 8
                    })
                    _this.payVisible = false
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 获取是否设置过交易密码
        getHasPaypassword(accountId){
            let _this = this
            getHasPayPassword(accountId)
            .then(res=>{
                if(res.success){
                    _this.hasPayPassword = res.data;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        selAccount(e){
            this.getHasPaypassword(e.target.value)
            var account = this.accountList.find(item => item.id == e.target.value);
            if(account.needDealPassword == '1'){
                this.needPayPassword = true;
            }else{
                this.needPayPassword = false;
            }
        }
    }
}

</script>
<style scoped>

</style>